package org.javaweb.cms_web.controller;

import org.javaweb.cms_web.mapper.PermissionMapper;
import org.javaweb.cms_web.model.Achievement;
import org.javaweb.cms_web.model.Enum.PermissionTypes;
import org.javaweb.cms_web.model.User;
import org.javaweb.cms_web.model.UserPermission;
import org.javaweb.cms_web.service.AchievementService;
import org.javaweb.cms_web.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
public class AchievementController {

    @Autowired
    private AchievementService achievementService;
    @Autowired
    private HostHolder hostHolder;
    @Resource
    private PermissionMapper permissionMapper;

    // 显示科研成果管理页面，展示所有科研成果
    @GetMapping("/admin/achievementmanagement")
    public String showAchievementsList(
            @RequestParam(value = "title", required = false) String title,
            @RequestParam(value = "category", required = false) Integer category,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate,
            Model model) {

        User user = hostHolder.getUser();
        List<UserPermission> list=permissionMapper.getPermissionsByUserId(user.getUserId());
        if (list.stream().map(UserPermission::getPermissionType).
                noneMatch(type -> type == PermissionTypes.SCIENTIFIC_RESEARCH_MANAGE.value)) {
            return "nopermission";
        }

        List<Achievement> achievements = achievementService.getAchievements(title, category, startDate, endDate);
        model.addAttribute("achievements", achievements);
        return "achievement-management";  // 返回到科研成果管理页面
    }

    // 删除科研成果
    @GetMapping("/admin/achievements/delete/{id}")
    public String deleteAchievement(@PathVariable("id") Integer achievementId, Model model) {
        boolean success = achievementService.deleteAchievement(achievementId);
        if (success) {
            model.addAttribute("message", "成果删除成功");
        } else {
            model.addAttribute("message", "成果删除失败");
        }
        // 删除后重新展示所有成果
        return "redirect:/admin/achievementmanagement";  // 重定向回成果列表页
    }


    // 显示新增成果页面
    @GetMapping("/admin/achievements/new")
    public String showCreatePage(Model model) {
        model.addAttribute("achievement", new Achievement());  // 添加空的 Achievement 对象
        return "achievement-create";  // 显示新增科研成果的表单页面
    }

    @PostMapping("/admin/achievements")
    public String saveAchievement(
            @ModelAttribute("achievement") Achievement achievement,
            @RequestParam("attachmentFile") MultipartFile attachmentFile,
            @RequestParam("pictureFile") MultipartFile pictureFile,
            BindingResult result,
            Model model) {

        try {
            // 保存附件文件
            if (!attachmentFile.isEmpty()) {
                String attachmentPath = saveFile(attachmentFile, "D:\\keshedata\\AchievementsAttachment\\");
                achievement.setAttachmentLink(attachmentPath); // 设置附件路径
            }

            // 保存图片文件
            if (!pictureFile.isEmpty()) {
                String picturePath = saveFile(pictureFile, "D:\\keshedata\\AchievementsPicture\\");
                achievement.setPictureLink(picturePath); // 设置图片路径
            }

            Integer userid=hostHolder.getUser().getUserId();
            achievement.setUserId(userid);
            achievement.setTeamId(1);
            // 调用服务层保存成果记录
            boolean success = achievementService.createAchievement(achievement);
            model.addAttribute("message", success ? "成果发布成功" : "成果发布失败");
        } catch (IOException e) {
            model.addAttribute("message", "文件上传失败：" + e.getMessage());
        }

        return "redirect:/admin/achievementmanagement";
    }
    // 辅助方法：保存文件到指定目录
    private String saveFile(MultipartFile file, String directory) throws IOException {
        // 确保目录存在
        File dir = new File(directory);
        if (!dir.exists()) {
            dir.mkdirs(); // 创建目录
        }

        // 生成唯一文件名
        String fileName = file.getOriginalFilename();
        File destination = new File(dir, fileName);

        // 保存文件到目标路径
        file.transferTo(destination);

        // 返回保存路径
        return destination.getAbsolutePath();
    }

    // 显示编辑页面
    @GetMapping("/admin/achievements/edit/{id}")
    public String showEditPage(@PathVariable("id") Integer achievementId, Model model) {
        Achievement achievement = achievementService.getAchievementById(achievementId);
        model.addAttribute("achievement", achievement);
        return "achievement-edit";  // 显示编辑成果的页面
    }

    @PostMapping("/admin/achievements/edit")
    public String editAchievement(
            @ModelAttribute("achievement") Achievement achievement,
            @RequestParam(value = "attachmentFile", required = false) MultipartFile attachmentFile,
            @RequestParam(value = "pictureFile", required = false) MultipartFile pictureFile,
            Model model) {

        try {

            if (attachmentFile != null && !attachmentFile.isEmpty()) {
                String attachmentPath = saveFile(attachmentFile, "D:\\keshedata\\AchievementsAttachment\\");
                achievement.setAttachmentLink(attachmentPath); // 更新附件路径
            }


            if (pictureFile != null && !pictureFile.isEmpty()) {
                String picturePath = saveFile(pictureFile, "D:\\keshedata\\AchievementsPicture\\");
                achievement.setPictureLink(picturePath); // 更新图片路径
            }

            Integer userid=hostHolder.getUser().getUserId();
            achievement.setUserId(userid);
            achievement.setTeamId(1);
            // 更新成果记录
            boolean success = achievementService.updateAchievement(achievement);
            model.addAttribute("message", success ? "成果修改成功" : "成果修改失败");
        } catch (IOException e) {
            model.addAttribute("message", "文件上传失败：" + e.getMessage());
        }

        return "redirect:/admin/achievementmanagement";
    }

    // 公开成果
    @GetMapping("/admin/achievements/public/{id}")
    public String publicAchievement(@PathVariable("id") Integer achievementId, Model model) {
        boolean success = achievementService.updateVisibility(achievementId, 0);  // 0 表示公开
        if (success) {
            model.addAttribute("message", "成果已公开");
        } else {
            model.addAttribute("message", "成果公开失败");
        }
        return "redirect:/admin/achievementmanagement";  // 重定向回成果列表页
    }

    // 隐藏成果
    @GetMapping("/admin/achievements/private/{id}")
    public String privateAchievement(@PathVariable("id") Integer achievementId, Model model) {
        boolean success = achievementService.updateVisibility(achievementId, 1);  // 1 表示隐藏
        if (success) {
            model.addAttribute("message", "成果已隐藏");
        } else {
            model.addAttribute("message", "成果隐藏失败");
        }
        return "redirect:/admin/achievementmanagement";  // 重定向回成果列表页
    }
}
